package com.example.demo.controller;


import com.example.demo.Service.LikeService;
import com.example.demo.Service.PostService;
import com.example.demo.Service.StarService;
import com.example.demo.entity.Post;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;
    private LikeService likeService;
    private StarService starService;

    //获取所有文章
    @GetMapping
    public List<Post> getAllPosts() {
        return postService.findAll();
    }

    //获取单篇文章详情
    @GetMapping("/{id}")
    public Post getPostById(@PathVariable Long id) {
        return postService.findById(id);
    }

    //查找特定用户的文章
    @GetMapping("/userbyId/{userId}")
    public List<Post> getPostsByUser(@PathVariable Long userId) {
        User user = new User();
        user.setId(userId);
        return postService.findByUser(user);
    }

    //根据标签查找文章
    @GetMapping("/tag/{tag}")
    public List<Post> getPostsByTag(@PathVariable String tag) {
        return postService.findByTag(tag);
    }

    //根据用户和标签查找文章
    @GetMapping("/userbyId/{userId}/tag/{tag}")
    public List<Post> getPostsByUserAndTag(@PathVariable Long userId, @PathVariable String tag) {
        User user = new User();
        user.setId(userId);
        return postService.findByUserAndTag(user, tag);
    }

    //根据用户名查找文章
    @GetMapping("/user/{username}")
    public List<Post> getPostsByUsername(@PathVariable String username) {
        return postService.findByUsername(username);
    }

    //根据用户名和标签查找文章
    @GetMapping("/user/{username}/tag/{tag}")
    public List<Post> getPostsByUsernameAndTag(@PathVariable String username, @PathVariable String tag) {
        return postService.findByUsernameAndTag(username, tag);
    }

    //创建或更新文章
    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }

    //删除文章
    @DeleteMapping("/{id}")
    public void deletePost(@PathVariable Long id) {
        postService.deleteById(id);
    }

    //统计文章点赞数
    @GetMapping("/{id}/likes/count")
    public Long getLikesCount(@PathVariable Post post) {
        return likeService.countLikesByPost(post);
    }

    //统计文章收藏数
    @GetMapping("/{id}/stars/count")
    public Long getStarsCount(@PathVariable Post post) {
        return starService.countStarsByPost(post);
    }
}
